<template>
  <div class='home'>
    <div class="bg"></div>
    <div class="cover"></div>
    <div class="bigbox">
      <!-- 搜索 -->
      <van-search v-model="value" shape="round" right-icon="search" left-icon="" placeholder="搜索关键词" @click="jump('search')" readonly>
        <template #label>
          <div class="label">
            <van-icon :name="require('@/assets/img/location.png')" @click="locpopup=true" />
            <span class="position">{{locations}}</span>
          </div>
        </template>
      </van-search>
      <!-- 轮播图 -->
      <div class="my-swipe-box">
        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
          <van-swipe-item v-for="(item, index) in banner1" :key="index"><img :src="`${resourceURL}${item.pic_url}`" alt="">
          </van-swipe-item>
        </van-swipe>
      </div>
      <!-- 导航菜单 -->

      <div class="btnList">
        <div class="top">
          <div class="topBtn" v-for="(item, index) in btnList1" :key="index" @click="jump(item.routeName)">
            <div class="img">
              <van-image :src="item.url" />
            </div>
            <p>{{ item.name }}</p>
          </div>

        </div>
        <!-- 邀请好友宣传图 -->

        <div class="inviteImg" @click="$router.push({name:'invite' })">
          <van-image :src="require('../assets/img/invite.png')" />
        </div>

        <div class="bottom">
          <div class="bottomBtn" v-for="(item, index) in btnList2" :key="index" @click="jump(item.routeName)">
            <div class="img">
              <van-image :src="item.url" />
            </div>
            <p>{{ item.name }}</p>
          </div>
        </div>
      </div>

      <div class="new">
        <div class="new-top">
          <div style="color: #202327;font-size: 16px;font-weight: bold;">家政护理 <span>品质生活，从洁净开始</span></div>
          <router-link to="/Housekeeping" tag="div">
            <van-icon name="arrow" />
          </router-link>
        </div>
        <div class="my-swipe-box" style="margin-top:0">
          <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
            <van-swipe-item v-for="(item, index) in banner2" :key="index"><img :src="`${resourceURL}${item.pic_url}`" alt="">
            </van-swipe-item>
          </van-swipe>
        </div>
      </div>

      <div class="new">
        <div class="new-top">
          <div style="color: #202327 ;font-size: 16px;font-weight: bold;">新势力速递 <span>精选热买新品</span></div>
          <router-link to="/NewProduct" tag="div">
            <van-icon name="arrow" />
          </router-link>
        </div>
        <div :class="['new-product' ,newList.length<3? 'noEnough':'']">
          <div class="item" v-for="(item, index) in this.newList" :key="index" @click="jumptoProduct(item)">
            <div class="img">
              <van-image class="cover_img" :src="`${resourceURL}${item.imageurl}`" fit="cover" />
            </div>
            <div class="price">新品价<span style="font-size:10px">￥</span>{{ item.price }}</div>
          </div>
        </div>
      </div>

      <div>

        <van-list v-model="loading" :finished="finished" @load="onLoad" :error.sync="err" error-text="加载失败，点击这里重试">
          <RowsList :list="list" style="margin-top:12px"></RowsList>
        </van-list>
      </div>

    </div>
    <van-popup v-model="locpopup" position="bottom" :style="{ height: '100%' }">
      <iframe id="mapPage" width="100%" height="100%" frameborder=0 src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=XQWBZ-ORU64-TLBUL-X423L-TTO3Z-WQBUX&referer=myapp"></iframe>
      <div class="select_location">
        <van-button type="primary" size="small" round plain @click="cancelSelectLocation" class="cancel">取消</van-button>
        <van-button type="primary" size="small" round @click="confirmSelectLocation">确认</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import RowsList from '../components/rowsList.vue'
import wxsdk from "../utils/wxsdk";

import { Toast } from 'vant'
export default {
  components: { RowsList },
  data () {
    return {
      locations: '未知',
      value: '',
      GroupmealList: [],
      list: [],
      ShopLists: [],
      locpopup: false,
      banner1: [],
      banner2: [],
      loading: false,
      finished: true,
      err: false,
      btnList1: [
        { url: require('../assets/img/home/Housekeeping.png'), name: '家政服务', routeName: 'Housekeeping' },
        { url: require('../assets/img/home/choose.png'), name: '大狮甄选', routeName: 'category' },
      ],
      btnList2: [
        { url: require('../assets/img/home/new.png'), name: '新品发布', routeName: 'NewProduct' },
        { url: require('../assets/img/home/couseIcon.png'), name: '优惠领券', routeName: 'coupon' },
        { url: require('../assets/img/home/member.png'), name: '会员空间', routeName: 'memberSpace' },
        { url: require('../assets/img/home/shopping.png'), name: '积分商城', routeName: 'ExchangeGoods' },
      ],
      newList: [],
      page: 1,
      address: {
        longitude: "", latitude: "", locations: ""
      }

    }
  },
  created () {
    let location = JSON.parse(localStorage.getItem('location'))
    const ua = navigator.userAgent.toLowerCase();
    var isIOS = ua.match(/iphone|ipod|ipad|Macintosh/i);
    if (location) {
      this.location = this.address.locations
    }
    if (this.$store.state.token && !location) {
      if (isIOS && JSON.parse(localStorage.getItem("updatePage")) == 1) {
        window.location.reload();
        localStorage.removeItem('updatePage')
      }

      this.getLocations()
    }

    this.productlist()
    this.getSwiper()
    this.getNewList()
    this.getCityName()
    this.$nextTick(() => {

      window.addEventListener('message', (event) => {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        let loc = event.data;
        if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          console.log(loc);
          this.address.longitude = loc.latlng.lng
          this.address.latitude = loc.latlng.lat
          this.address.locations = loc.cityname.replace('市', '')
          console.log(this.locations);
        }
      }, false);
    });

  },
  beforeDestroy () {
    window.removeEventListener('message', (event) => {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      let loc = event.data;
      if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        console.log(loc);
        this.address.longitude = loc.latlng.lng
        this.address.latitude = loc.latlng.lat
        this.address.locations = loc.cityname.replace('市', '')
        console.log(this.locations);
      }
    }, false)
  },
  methods: {
    // 取消选择地理位置
    cancelSelectLocation () {

      this.address.longitude = ''
      this.address.latitude = ''
      this.address.locations = ''
      this.locpopup = false
    },
    // 确认选择地理位置
    confirmSelectLocation () {
      console.log(this.address);
      this.locations = this.address.locations
      localStorage.setItem('location', JSON.stringify(this.address))
      this.locpopup = false
    },
    //获取位置
    getLocations () {

      if (this.$store.state.token) {
        wxsdk().then((wx) => {
          wx.getLocation({
            type: 'gcj02', // 默认为wgs84的 gps 坐标，如果要返回直接给 openLocation 用的火星坐标，可传入'gcj02'
            success: (resolve) => {

              localStorage.setItem('location', JSON.stringify(resolve))
              this.getCityName()
            },
            fail: () => {
              Toast.fail('位置信息获取失败')

            }
          })
        })
      }

    },
    //根据经纬度获取地址
    getCityName () {
      let location = JSON.parse(localStorage.getItem('location'))
      if (location) {
        this.$axios.post(this.$api.maprequest, {
          lon: location.longitude,
          lat: location.latitude,
        }).then((res) => {
          if (res.data.code == 1) {
            //this.arr.push(res.data.data.data);

            this.locations = (res.data.data.address_component.city).replace('市', '')
          }

        })
      }
    },
    onLoad () {
      this.page++
      this.productlist()

    },

    jumptoProduct (item) {

      this.$router.push({
        name: 'product',
        query: {
          id: item.product_id
        }

      })
    },


    getSwiper () {

      this.$axios.get(this.$api.swiper).then((res) => {
        if (res.data.code == 1) {
          //this.arr.push(res.data.data.data);

          this.banner1 = res.data.data.banner1
          this.banner2 = res.data.data.banner2

        }

      })
    },

    // 普通商品列表
    productlist () {
      this.loading = true
      this.$axios.get(this.$api.productlist, {
        params: {
          page: this.page,
          limit: '10',
          show: '1',
          is_page: '2',
          sort: '2',
        }
      }).then((res) => {
        this.loading = false
        this.searchBtn = false

        if (res.data.code == 1) {
          if (res.data.data.length == 0) {
            this.finished = true
          } else {
            this.list = this.list.concat(res.data.data);
            this.finished = false

          }

        } else {
          this.err = true;
          this.loading = false;
        }

        // console.log(this.list);

      })
    },
    // 普通商品列表
    getNewList () {
      this.loading = true
      this.$axios.get(this.$api.productlist, {
        params: {
          page: this.page,
          limit: '10',
          show: '2',
          is_page: '2',
          sort: '2',

        }
      }).then((res) => {

        if (res.data.code == 1) {
          console.log(res);
          this.newList = res.data.data

        }

        // console.log(this.list);

      })
    },

    //跳转模块
    jump (name) {

      this.$router.push({
        name: name,

      })
    },
    // 获取微信授权URL
    getWxUserInfo () {

      this.$axios.post(this.$api.Authorize, {
        url: window.location.href
      }).then(res => {
        this.getWxCode(res.data.data.url)
      })

    },
    // 微信授权获取用户信息
    getWxCode (url) {
      this.code = this.getUrlCode().code;
      //如果没有code 去获取code
      if (this.code == null) {
        window.location.href = url
      } else {
        this.$axios.post(this.$api.Authlogin, {
          code: this.code,
          state: 'STATE',
        }).then(res => {

          if (res.data.code != 1) {
            Toast.fail('登录失败')
          } else {
            this.$store.commit('settoken', res.data.data.token);
          }
        })
      }
    },
    //截取code
    getUrlCode () { // 截取url中的code方法
      var url = location.search
      var theRequest = new Object()
      if (url.indexOf("?") != -1) {
        var str = url.substr(1)
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
        }
      }
      return theRequest
    },





  }
}
</script>

<style scoped lang='less'>
/deep/.van-search {
  background-color: transparent !important;
  padding: 12px 0;
  .label {
    display: flex;
    align-items: center;
    font-size: 12px;
    .position {
      margin: 0 14px 0 6px;
    }
  }
}
.noEnough {
  justify-content: flex-start !important;

  .item {
    margin-right: 10px;
  }
}
/deep/.van-search {
  background-color: transparent !important;
  padding: 0;
  margin-top: 12px;
}

/deep/.van-notice-bar {
  background-color: transparent !important;
  color: black;
}

.my-swipe-box {
  margin-top: 18px;
  border-radius: 15px;
  overflow: hidden;
  transform: translateY(0);

  .my-swipe .van-swipe-item {
    text-align: center;

    img {
      width: 100%;
      height: 150px;
      // border-radius: 10px;
    }
  }
}

.cover {
  position: absolute;
  width: 100%;
  height: 20px;
  border-radius: 10px;
  top: 190px;
  z-index: 0;
  background: white;
}

.bigbox {
  transform: translateY(-200px);
  width: 100%;
  padding: 0 16px;
  box-sizing: border-box;
}
.inviteImg {
  width: 343px;
  height: 74px;
  margin-top: 12px;
}
.home {
  position: relative;
  padding-bottom: 50px;
  min-height: 100vh;
  background: #fff;

  .bg {
    //padding-bottom: 50px;
    // position: absolute;
    // top: 0;
    height: 200px;
    background: linear-gradient(180deg, #ff7733 0%, #ffcfb7 100%);
    opacity: 1;
  }
  .new-top {
    height: 38px;
    //background: url(../assets/img/home/appointment.png) no-repeat;
    background-size: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      font-size: 12px;
      font-family: Microsoft YaHei-Regular, Microsoft YaHei;
      font-weight: 400;
      color: rgba(32, 35, 39, 0.6);
      margin-left: 6px;
    }

    .more {
      background: url(../assets/img/home/more.png) no-repeat;
      background-size: 100%;
      width: 14.49867vw;
      height: 5.26667vw;
      font-size: 2.66667vw;
      color: #d56869ff;
      text-align: center;
    }
  }
  .new {
    // margin: 16px 0 19px 0;
    // height: 176px;
    // background: #ffffff;
    // box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.06);
    // opacity: 1;
    // border-radius: 10px;
    margin-bottom: 12px;
    overflow-x: scroll;
    .new-top {
      height: 38px;
      //background: url(../assets/img/home/appointment.png) no-repeat;
      background-size: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        font-size: 12px;
        font-family: Microsoft YaHei-Regular, Microsoft YaHei;
        font-weight: 400;
        color: rgba(32, 35, 39, 0.6);
        margin-left: 6px;
      }

      .more {
        background: url(../assets/img/home/more.png) no-repeat;
        background-size: 100%;
        width: 14.49867vw;
        height: 5.26667vw;
        font-size: 2.66667vw;
        color: #d56869ff;
        text-align: center;
      }
    }

    .new-product {
      display: flex;
      justify-content: space-between;
      overflow-x: scroll;
      .item {
        width: 110px;
        box-sizing: border-box;
        background: #ffffff;
        box-shadow: 0px 3px 10px 1px rgba(1, 12, 27, 0.06);
        border-radius: 6px 6px 6px 6px;
        display: flex;
        flex-direction: column;
        align-items: center;

        padding: 6px;

        .img {
          /deep/ .van-image {
            width: 78px;
            height: 78px;
          }
        }

        .price {
          margin-top: 6px;
          width: 96px;
          height: 24px;
          border-radius: 11px;
          background: linear-gradient(90deg, #f38f5d 0%, #ff7733 100%);
          font-size: 12px;
          font-family: Microsoft YaHei-Regular, Microsoft YaHei;
          font-weight: 400;
          color: #ffffff;
          text-align: center;
          line-height: 24px;
        }
      }
    }
    .new-product::-webkit-scrollbar {
      display: none; /* Chrome Safari */
    }
  }
}

.btnList {
  margin-top: 12px;
  margin-bottom: 15px;
  box-sizing: border-box;

  .top {
    display: flex;
    justify-content: space-between;

    .topBtn {
      width: 168px;
      height: 80px;
      background: #ffffff;
      box-shadow: 0px 1px 10px 1px rgba(1, 12, 27, 0.04);
      border-radius: 6px 6px 6px 6px;
      opacity: 1;
      display: flex;
      align-items: center;
      box-sizing: border-box;
      padding: 12px;

      .img {
        /deep/ .van-image {
          width: 56px;
          height: 56px;
        }
      }

      p {
        margin: 0;
        margin-left: 12px;
        font-size: 14px;
        font-family: Microsoft YaHei-Bold, Microsoft YaHei;
        font-weight: bold;
        color: #202327;
      }
    }
  }

  .bottom {
    background: #ffffff;
    box-shadow: 0px 3px 6px 1px rgba(1, 12, 27, 0.04);
    border-radius: 6px 6px 6px 6px;
    width: 343px;
    height: 77px;
    margin-top: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 12px;
    box-sizing: border-box;

    .bottomBtn {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .img {
        /deep/ .van-image {
          width: 23px;
          height: 20px;
        }
      }

      p {
        margin: 0;
        margin-top: 6px;
        font-size: 12px;
        font-family: Microsoft YaHei-Regular, Microsoft YaHei;
        font-weight: 400;
        color: rgba(6, 2, 26, 0.6);
      }
    }
  }
}

.Box {
  position: absolute;
  height: 5px;
  width: 100%;
}

.courseList {
  .itemBox {
    margin-bottom: 12px;
    width: 343px;
    height: 106px;
    background: #ffffff;
    box-shadow: 0px 3px 10px 1px rgba(1, 12, 27, 0.06);
    border-radius: 6px 6px 6px 6px;
    display: flex;
    .left {
      .van-image {
        width: 140px;
        height: 106px;
      }
    }
    .right {
      flex: 1;
      padding: 12px;
      display: flex;
      justify-content: space-between;
      flex-direction: column;
      .name {
        font-size: 14px;
        color: #120320;
      }
      .bottom {
        display: flex;
        justify-content: space-between;
        .price {
          font-size: 16px;
          font-family: Microsoft YaHei-Bold, Microsoft YaHei;
          font-weight: bold;
          color: #f33224;
        }
        .num {
          font-size: 12px;

          color: rgba(24, 22, 25, 0.6);
        }
      }
    }
  }
}
.select_location {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  padding: 20px;
  box-sizing: border-box;
  .van-button {
    width: 100px;
    font-weight: bold;
    font-size: 14px;
    color: white;
  }
  .cancel {
    border: none;
    //border: 1px solid rgba(0, 0, 0, 0.3);
    background: rgba(0, 0, 0, 0.3);
  }
}
</style>
